<template>
    <div class="col-12">
        <div class="row">
            <div class="col-sm-6">
                <div class="card shadow-sm border-0">
                    <div class="card-body">
                        <h4 class="card-title mb-0">{{ keywords }}</h4>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                <ul class="list-group border-0 shadow-sm">
                    <li class="list-group-item list-group-item-action border-0" v-for="track in tracks" :key="track.id" @click="playTrack(track.id)">
                        {{ track.name }}
                        <div class="ml-auto text-muted" v-for="artist in track.artists" :key="artist.id">
                            {{ artist.name }}
                        </div>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: "search",
        data() {
            return {
                keywords: '',
                tracks: [],
            }
        },
        created() {
            this.keywords = this.$route.query.q
            this.getSearchResults(this.keywords)
        },
        watch: {
            $route() {
                this.keywords = this.$route.query.q
                this.getSearchResults(this.keywords)
            }
        },
        methods: {
            getSearchResults(keywords) {
                this.$http.get(`/api/search?keywords=${keywords}`).then(response => {
                    this.tracks = response.data.result.songs
                })
            },
            playTrack(id) {
                this.$store.dispatch('setPlayTrackAction', { id: id })
            }
        }
    }
</script>